<template>
  <div class="recent-exercises">
    <div class="page-header">
      <h2>Recent Exercises</h2>
      <div class="header-actions">
        <el-select v-model="timeFilter" placeholder="Time Period" size="default">
          <el-option label="Last 7 days" value="7days" />
          <el-option label="Last 30 days" value="30days" />
          <el-option label="Last 3 months" value="3months" />
          <el-option label="All time" value="all" />
        </el-select>
        <el-button type="primary" @click="refreshExercises">
          <el-icon><Refresh /></el-icon>
          Refresh
        </el-button>
      </div>
    </div>

    <div class="exercises-container">
      <el-card v-if="loading" class="loading-card">
        <el-skeleton :rows="5" animated />
      </el-card>

      <div v-else-if="exercises.length === 0" class="empty-state">
        <el-empty description="No recent exercises found">
          <el-button type="primary" @click="goToExercises">Browse Exercises</el-button>
        </el-empty>
      </div>

      <div v-else class="exercises-list">
        <el-table :data="exercises" style="width: 100%" border>
          <el-table-column prop="title" label="Exercise Title" min-width="200">
            <template #default="{ row }">
              <div class="exercise-title">
                <span>{{ row.title }}</span>
                <el-tag size="small" type="info">{{ row.category }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastAttempted" label="Last Attempted" width="180">
            <template #default="{ row }">
              {{ formatDate(row.lastAttempted) }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="Score" width="120">
            <template #default="{ row }">
              <div class="score-display">
                <el-progress 
                  :percentage="row.score" 
                  :color="getScoreColor(row.score)"
                  :stroke-width="10"
                />
                <span>{{ row.score }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="timeSpent" label="Time Spent" width="120">
            <template #default="{ row }">
              {{ formatTime(row.timeSpent) }}
            </template>
          </el-table-column>
          <el-table-column label="Actions" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="viewExercise(row.id)">
                  View
                </el-button>
                <el-button type="success" size="small" @click="practiceExercise(row.id)">
                  Practice Again
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container" v-if="exercises.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalExercises"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'RecentExercises',
  components: {
    Refresh
  },
  setup() {
    const router = useRouter()
    const exercises = ref([])
    const loading = ref(true)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalExercises = ref(0)
    const timeFilter = ref('7days')

    const fetchExercises = async () => {
      loading.value = true
      try {
        // Replace with actual API call
        // const response = await api.getRecentExercises({
        //   page: currentPage.value,
        //   pageSize: pageSize.value,
        //   timePeriod: timeFilter.value
        // })
        // exercises.value = response.data.exercises
        // totalExercises.value = response.data.total

        // Mock data for now
        setTimeout(() => {
          exercises.value = [
            {
              id: 1,
              title: 'JavaScript Basics',
              category: 'Programming',
              lastAttempted: new Date().toISOString(),
              score: 85,
              timeSpent: 1800 // seconds
            },
            {
              id: 2,
              title: 'Vue.js Components',
              category: 'Web Development',
              lastAttempted: new Date(Date.now() - 86400000).toISOString(), // yesterday
              score: 92,
              timeSpent: 2400 // seconds
            },
            {
              id: 3,
              title: 'CSS Flexbox',
              category: 'Web Design',
              lastAttempted: new Date(Date.now() - 172800000).toISOString(), // 2 days ago
              score: 70,
              timeSpent: 1200 // seconds
            }
          ]
          totalExercises.value = 3
          loading.value = false
        }, 1000)
      } catch (error) {
        console.error('Error fetching recent exercises:', error)
        ElMessage.error('Failed to load recent exercises')
        loading.value = false
      }
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchExercises()
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchExercises()
    }

    const refreshExercises = () => {
      fetchExercises()
    }

    const viewExercise = (id) => {
      router.push(`/dashboard/exercises/${id}`)
    }

    const practiceExercise = (id) => {
      router.push(`/dashboard/exercises/${id}/practice`)
    }

    const goToExercises = () => {
      router.push('/dashboard/exercises')
    }

    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    const formatTime = (seconds) => {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}m ${remainingSeconds}s`
    }

    const getScoreColor = (score) => {
      if (score >= 90) return '#67C23A' // success
      if (score >= 70) return '#E6A23C' // warning
      return '#F56C6C' // danger
    }

    watch(timeFilter, () => {
      fetchExercises()
    })

    onMounted(() => {
      fetchExercises()
    })

    return {
      exercises,
      loading,
      currentPage,
      pageSize,
      totalExercises,
      timeFilter,
      handleSizeChange,
      handleCurrentChange,
      refreshExercises,
      viewExercise,
      practiceExercise,
      goToExercises,
      formatDate,
      formatTime,
      getScoreColor
    }
  }
}
</script>

<style scoped>
.recent-exercises {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.exercises-container {
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 20px;
}

.loading-card {
  margin-bottom: 20px;
}

.empty-state {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.exercise-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.score-display {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 